package com.csun.cmny.mqtt.app;

import com.csun.cmny.mqtt.core.DeviceDataBase;
import com.csun.cmny.mqtt.core.MqttClientBase;
import com.csun.cmny.mqtt.core.MqttClientSubCallback;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2019-01-15 15:13
 * @Description:
 */
@Slf4j
public class MqttClientSub extends MqttClientBase {

    private static MqttClientSub mqttClientSub = new MqttClientSub();
    private int[] qos;
    private String[] topic;

    public static MqttClientSub getMqttClientSub() {
        return mqttClientSub;
    }

    @Override
    public boolean mqttClientStart(int[] qos, String[] topic,
                                   DeviceDataBase deviceData) throws MqttException {

        /* 创建mqtt订阅客户端 */
        mqttClient = new MqttClient(url, clientId, new MemoryPersistence());
        /* mqtt订阅端设置回调函数 */
        mqttClient.setCallback(new MqttClientSubCallback(deviceData));
        /* mqtt订阅端连接服务器 */
        mqttClient.connect(options);
        /* 订阅主题和消息级别 */
        mqttClient.subscribe(topic, qos);

        return true;
    }

    @Override
    public boolean mqttClientReConn() {
        log.warn("MqttClientSub:mqttClientReConn");
        try {
            mqttClient.connect(options);
            mqttClient.subscribe(topic, qos);
        } catch (MqttException e) {
            e.printStackTrace();
        }

        return true;
    }
}
